﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Ysb.Components;
using BLL;
using Model;
using System.Xml;
public partial class Admin_BillShow : System.Web.UI.Page
{
    public string Mg;
    public string NotMg;
    public string IsMg;
    public string BaozhuangFL;
    public string DaigouFl;
    public string IsHaveFendan;
    public string seph;
    Tools tool = new Tools();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!AdminCheck.Check(this, 1))
        {
            Response.Redirect(AdminCheck.RedirectPage);
            return;
        }
        if (!Page.IsPostBack)
        {

            if (Request.UrlReferrer != null)
            {
                if (Request.UrlReferrer.ToString().IndexOf("BillManaga.aspx") > 0)
                {

                    Session["url"] = Request.UrlReferrer.ToString();
                }
            }

            //  Response.Write(Session["url"]);

            if (Request.QueryString["Tno"] == null && Request.QueryString["Tno"].ToString().Trim() == "")
            {

                Jscript.AlertAndGoBack("请按正常操作单据！");
                return;
            }
            XmlDocument Document = new XmlDocument();
            Document.Load(ApplicationInfo.PhysicalApplicationPath + "Config/AppConfig.config");
            Mg = Document.GetElementsByTagName("set1").Item(0).Attributes["value"].Value;
            NotMg = Document.GetElementsByTagName("set2").Item(0).Attributes["value"].Value;

            BindDDL();
            BindWallBill(Request.QueryString["Tno"].ToString());
            BindSepNo(Request.QueryString["Tno"].ToString());
            BinDataState(Request.QueryString["Tno"].ToString());
            BindLiuYan(Request.QueryString["Tno"].ToString());


            Rpt_Name.DataSource = new PublicSqlService().GetData("GoodsName", "Tbl_SplitBillGoods", "");
            Rpt_Name.DataBind();

        }
    }

    void BindSepNo(string tn)
    {
        DataTable dt = new PublicSqlService().GetData("SepNo,SBState,TrackingNo,SendBy,CHNReceiver,Pieces,ChargedWt,FlightNo,Total,CreateDate,logo", "Tbl_SepBill", "TrackingNo='" + tn + "'");

        if (dt.Rows.Count == 0)
        {
            IsHaveFendan = "0";
        }
        else
        {
            IsHaveFendan = "1";
        }
        sepshow.DataSource = dt;
        sepshow.DataBind();


        seph = (26 * dt.Rows.Count).ToString();

    }
    void GetUser(string id)
    {

        DataTable dt = new PublicSqlService().GetData("*", "TblUserInfo", "Uid=" + id);
        if (dt.Rows.Count == 0)
        {
            Tools.OpenWindow(this, "公司信息异常，请联系管理人员");
            return;
        }

        lbgsr.Text = dt.Rows[0]["TrueName"].ToString();
		 Email.Value = dt.Rows[0]["Email"].ToString();
        // sendertxt.Value = dt.Rows[0]["TrueName"].ToString();
        // phonenotxt.Value = dt.Rows[0]["Tel"].ToString();
        // companytxt.Value = dt.Rows[0]["Company"].ToString();
        // addtxt.Value = dt.Rows[0]["Address"].ToString();
        creaduser.Value = id;
        if (dt.Rows[0]["Country"].ToString().Trim() == "美国")
        {
            IsMg = "true";
        }
        else
        {
            IsMg = "false";
        }
		
		
        DataTable ndt = new PublicSqlService().GetData("*", "Tb_UserProperty", "UserID=" + id);

        BaozhuangFL = ndt.Rows[0]["PackagingRate"].ToString();
        DaigouFl = ndt.Rows[0]["ShoppingServiceRate"].ToString();


    }
    void BinDataState(string tn)
    {
        DataTable dt = new PublicSqlService().GetData("*", "Tbl_BillStateRec", "SepNo='" + tn + "'");

        Sataterp.DataSource=dt;
        Sataterp.DataBind();
     
        
    }
    void BindLiuYan(string tn)
    {
        lyshow.DataSource = new PublicSqlService().GetData("*", "Tbl_Discuss", "Tno='" + tn + "'");
        lyshow.DataBind();
    }

    void BindWallBill(string tn)
    {
        tnlb.Text = tn;

        DataTable dt = new PublicSqlService().GetData("*", "Tbl_WayBill", "TrackingNo='" + tn.Trim() + "'");
        if (dt.Rows.Count != 1)
        {
            Jscript.AlertAndGoBack("单据单号：" + tn + " 数据异常！请记录单号联系管理人员！");
            return;
        }
        BindHuoWu(tn);
        GetUser(dt.Rows[0]["CreateUserID"].ToString());//人员绑定
      //  jifeitype.DataSource = new PayModelService().GetUserCalType(dt.Rows[0]["CreateUserID"].ToString());
		
		
		DataTable table1 = new PayModelService().GetUserCalType(dt.Rows[0]["CreateUserID"].ToString());   
		table1.Columns.Add("bbb", System.Type.GetType("System.String"), "name+'-'+Substring(cid,3,10)"); 
		jifeitype.DataSource = table1;
		
        jifeitype.DataTextField = "bbb";
        jifeitype.DataValueField = "cid";
        jifeitype.DataBind();


        #region   发送人基本属性
        sendertxt.Value = dt.Rows[0]["Sender"].ToString();
        dt.Rows[0]["FromFaxNo"].ToString();
        phonenotxt.Value = dt.Rows[0]["FromPhoneNo"].ToString();
        companytxt.Value = dt.Rows[0]["FromCompany"].ToString();
        addtxt.Value = dt.Rows[0]["FromAddress"].ToString();
        //dt.Rows[0]["FromCity"].ToString(); "");
        // dt.Rows[0]["FromState"].ToString(); "");
        // dt.Rows[0]["FromZIPCode"].ToString(); "");
        #endregion
        #region   收件人基本属性
        renametxt.Value = dt.Rows[0]["Receiver"].ToString();
        rephonenotxt.Value = dt.Rows[0]["ToPhoneNo"].ToString();
        recompanytxt.Value = dt.Rows[0]["ToCompany"].ToString();
        readdtxt.Value = dt.Rows[0]["ToAddress"].ToString();
        #endregion
        #region 其他相关属性
        FlightNotxt.Value = dt.Rows[0]["FlightNo"].ToString();//参考
        AerialNotxt.Value = dt.Rows[0]["AerialNo"].ToString();//航空单号
        companynamepy.Value = dt.Rows[0]["companynamepy"].ToString();//add
        namepy.Value = dt.Rows[0]["namepy"].ToString();//add
        tozipcode.Value = dt.Rows[0]["tozipcode"].ToString();//add
        website.Value = dt.Rows[0]["website"].ToString();//add
        chenshi.Value = dt.Rows[0]["chenshi"].ToString();//add
        TrackingNo.Value = dt.Rows[0]["TrackingNo"].ToString();//add
        qyd_ddr.Text = dt.Rows[0]["Origin"].ToString();
        mdd_ddr.Text = dt.Rows[0]["Destination"].ToString();


        //支付方式

        paylist.Text = dt.Rows[0]["Payment"].ToString();

        //包装形式

        huowulist.Text = dt.Rows[0]["Packing"].ToString();
        #endregion
        #region 质量 体积

        zhongliang_txt.Value = dt.Rows[0]["TotalWeight"].ToString();//重重量
        gaotxt.Value = dt.Rows[0]["DimensionsH"].ToString();
        changtxt.Value = dt.Rows[0]["DimensionsL"].ToString();
        kuantxt.Value = dt.Rows[0]["DimensionsW"].ToString();

        tijizhonglianghd.Value = dt.Rows[0]["DimensionsWeight"].ToString();

        #endregion
        #region  价格
        ChargedWt.Text = dt.Rows[0]["ChargedWt"].ToString(); //收费重量
        shoufeizhonglianghd.Value = dt.Rows[0]["ChargedWt"].ToString();
        FreightChargelb.Text = dt.Rows[0]["FreightCharge"].ToString();  //重量收费
        zlshoufeihd.Value = dt.Rows[0]["FreightCharge"].ToString();
        haiguanall.Text = dt.Rows[0]["DeclarePrice"].ToString(); //海关申报总价
        haiguanhd.Value = dt.Rows[0]["DeclarePrice"].ToString();
        dianfufeilb.Value = dt.Rows[0]["Memo2"].ToString();//垫付费

        daigoufeilb.Text = dt.Rows[0]["Memo3"].ToString();  //代购费

        daigoufeihd.Value = dt.Rows[0]["Memo3"].ToString();
        baozhuangfeilb.Text = dt.Rows[0]["Memo4"].ToString(); //包装费
        baozhuangfeihd.Value = dt.Rows[0]["Memo4"].ToString();
        guanshuitxt.Value = dt.Rows[0]["Duties"].ToString();  //关税
        baoxianfeitxt.Value = dt.Rows[0]["Premium"].ToString();//保险费
        othertxt.Value = dt.Rows[0]["OtherCharge"].ToString(); ;//其他费用
        youhuitxt.Value = dt.Rows[0]["Memo5"].ToString();  //优惠
        Totallb.Text = dt.Rows[0]["Total"].ToString();  //总费用
        Totalhb.Value = dt.Rows[0]["Total"].ToString();
        paytypehd.Value = dt.Rows[0]["Memo1"].ToString();  //计费类别

        string text = new WayBillService().GetCalTypeName(new Tools().StringToIntDif(dt.Rows[0]["Memo1"]).ToString());
        jifeitype.SelectedIndex = jifeitype.Items.IndexOf(jifeitype.Items.FindByText(text));


        //if (dt.Rows[0]["Stateid"].ToString().Trim() != "1")
        //{
        //    delbtn.Enabled = false;
        //}
        #endregion








    }
    //起运地 目的地
    void BindDDL()
    {
        qyd_ddr.DataSource = new PlaceService().GetStart();
        qyd_ddr.DataTextField = "PlaceName";
        qyd_ddr.DataBind();
        qyd_ddr.Items.Insert(0, "");
        mdd_ddr.DataSource = new PlaceService().GetEnd();
        mdd_ddr.DataTextField = "PlaceName";
        mdd_ddr.DataBind();
        mdd_ddr.Items.Insert(0, "");

 
        DAL.BillStateCollection  dtstate = new BillStateService().GetAllList();
        statelistdrr.DataSource = dtstate;
        statelistdrr.DataTextField = "Description";
        statelistdrr.DataValueField = "BSID";
        statelistdrr.DataBind();
        stateedit.DataSource = dtstate;
        stateedit.DataTextField = "Description";
        stateedit.DataValueField = "BSID";
        stateedit.DataBind();
        DAL.DomesticShippingCollection dc = new DomesticShippingService().GetAll();
        cplistdrr.DataSource = dc;
        cplistdrr.DataTextField = "CompanyName";
        cplistdrr.DataValueField = "ID";
        cplistdrr.DataBind();

        cplistdrr.Items.Insert(0, new ListItem("", "0"));


        gongsiedit.DataSource = dc;
        gongsiedit.DataTextField = "CompanyName";
        gongsiedit.DataValueField = "ID";
        gongsiedit.DataBind();

        gongsiedit.Items.Insert(0, new ListItem("", "0"));

        paylist.DataSource = new PayModelService().GetAll();
        paylist.DataTextField = "ModelName";
        paylist.DataValueField = "PID";
        paylist.DataBind();

    }
    //绑定获取
    void BindHuoWu(string NO)
    {

        DataTable dt = new PublicSqlService().GetData("*", "TblShipment", "TrackingNo='" + NO.Trim() + "'");

        if (dt.Rows.Count > 0)
        {


            if (dt.Rows.Count == 1)
            {
                name1.Value = dt.Rows[0]["Commodity"].ToString();
                num1.Value = dt.Rows[0]["Qty"].ToString();
                price1.Value = dt.Rows[0]["ValueForCustoms"].ToString();
                nameenglish1.Value = dt.Rows[0]["nameenglish"].ToString();


            }
            if (dt.Rows.Count > 1)
            {
                name1.Value = dt.Rows[0]["Commodity"].ToString();
                num1.Value = dt.Rows[0]["Qty"].ToString();
                price1.Value = dt.Rows[0]["ValueForCustoms"].ToString();
                nameenglish1.Value = dt.Rows[0]["nameenglish"].ToString();
                name2.Value = dt.Rows[1]["Commodity"].ToString();
                num2.Value = dt.Rows[1]["Qty"].ToString();
                price2.Value = dt.Rows[1]["ValueForCustoms"].ToString();
                nameenglish2.Value = dt.Rows[1]["nameenglish"].ToString();
            }

        }

    }
    //写入数据
    void ToInsert()
    {

        //if (sepshow.Items.Count > 0)
        //{
        //    Tools.OpenWindow(this, "当前单据已经存在分单不允许修改");
        //    return;
        //}


        if (!AdminCheck.HaveRight(this, "42"))
        {
            //未包含 编辑所有



            if (new PublicSqlService().GetCoun("BID", "Tbl_WayBill", "TrackingNo='" + Request.QueryString["Tno"].ToString().Trim() + "' and  Stateid=1 ") != 1)
            {
                  Jscript.AlertAndGoBack("当前单据已经不可编辑！你无权限编辑,请联系管理人员！");
             //   Response.Redirect("BillManaga.aspx");

            return;
            }

        }

        #region   发送人基本属性


        Hashtable hs = new Hashtable();




        hs.Add("Sender", sendertxt.Value);
        hs.Add("FromFaxNo", "");
        hs.Add("FromPhoneNo", phonenotxt.Value);
        hs.Add("FromCompany", companytxt.Value);
        hs.Add("FromAddress", addtxt.Value);

        #endregion
        #region   收件人基本属性








        hs.Add("Receiver", renametxt.Value);
        hs.Add("ToPhoneNo", rephonenotxt.Value);
        hs.Add("ToCompany", recompanytxt.Value);
        hs.Add("ToAddress", readdtxt.Value.Trim());


        #endregion
        #region 其他相关属性



        hs.Add("FlightNo", FlightNotxt.Value);//参考

        hs.Add("AerialNo", AerialNotxt.Value);//航空单号






        hs.Add("Origin", qyd_ddr.SelectedItem.Text);
        hs.Add("Destination", mdd_ddr.SelectedItem.Text);


        //支付方式

        hs.Add("Payment", paylist.SelectedItem.Value);







        //包装形式

        hs.Add("Packing", huowulist.SelectedItem.Value);



        //保价费













        #endregion
        #region 质量 体积

        hs.Add("TotalWeight", tool.StringToDecimalDif(StrHelper.VldNull(zhongliang_txt.Value)));//重重量
        hs.Add("DimensionsH", tool.StringToDecimalDif(StrHelper.VldNull(gaotxt.Value)));
        hs.Add("DimensionsL", tool.StringToDecimalDif(StrHelper.VldNull(changtxt.Value)));
        hs.Add("DimensionsW", tool.StringToDecimalDif(StrHelper.VldNull(kuantxt.Value)));



        hs.Add("DimensionsWeight", tool.StringToDecimalDif(StrHelper.VldNull(tijizhonglianghd.Value)));  //体积重量  起运地为美国

        #endregion
        #region  价格
        hs.Add("ChargedWt", tool.StringToDecimalDif(StrHelper.VldNull(shoufeizhonglianghd.Value)));//收费重量

        if (sepshow.Items.Count == 0)
        {
            hs.Add("SepChargedWt", tool.StringToDecimalDif(StrHelper.VldNull(shoufeizhonglianghd.Value)));//收费重量
        }
        hs.Add("FreightCharge", tool.StringToDecimalDif(zlshoufeihd.Value));//重量收费
        hs.Add("DeclarePrice", tool.StringToDecimalDif(haiguanhd.Value));//海关申报总价
        hs.Add("Memo2", tool.StringToDecimalDif(dianfufeilb.Value));//垫付费
        hs.Add("Memo3", tool.StringToDecimalDif(daigoufeihd.Value));//代购费
        hs.Add("Memo4", tool.StringToDecimalDif(baozhuangfeihd.Value));//包装费
        hs.Add("Duties", tool.StringToDecimalDif(guanshuitxt.Value));//关税
        hs.Add("Premium", tool.StringToDecimalDif(baoxianfeitxt.Value));//保险费
        hs.Add("OtherCharge", tool.StringToDecimalDif(othertxt.Value));//其他费用
        hs.Add("Memo5", tool.StringToDecimalDif(youhuitxt.Value));//优惠
        hs.Add("Total", tool.StringToDecimalDif(Totalhb.Value));//总费用
        if (sepshow.Items.Count == 0)
        {
            hs.Add("SepTotal", tool.StringToDecimalDif(Totalhb.Value));//总费用
        }
        hs.Add("Memo1", paytypehd.Value);//垫付费



        #endregion
        #region  状态

        if (new PublicSqlService().Update(hs, "Tbl_WayBill", "TrackingNo='" + Request.QueryString["Tno"].ToString().Trim() + "'"))
        {

            InsertHuowu(Request.QueryString["Tno"].ToString().Trim());


            if (Session["url"] != null && Session["url"].ToString().Trim() != "")
            {

            }
            else
            {
                Session["url"] = Request.Url.ToString();
            }


            Hashtable hs2 = new Hashtable();
            hs2.Clear();
            hs2.Add("admin", Session["UserName"].ToString());
            hs2.Add("Url", Session["url"]);
            hs2.Add("date", DateTime.Now);
            hs2.Add("trackingno", Request.QueryString["Tno"].ToString().Trim());
            hs2.Add("type", "modify order");
            hs2.Add("account", "");
            new PublicSqlService().Insert(hs2, "log");

            Tools.OpenWindow(this, "编辑成功！", Session["url"].ToString());

        }
        else
        {


            Tools.OpenWindow(this, "编辑失败！请重试");
            return;
        }
        #endregion



    }
    #region 获取写入编辑
    private void InsertHuowu(string acc)
    {

        //写入


        new PublicSqlService().Del("TblShipment", "TrackingNo='" + acc.Trim() + "'");
        Shipment sp = new Shipment();
        sp.Commodity = name1.Value;
        sp.TrackingNo = acc;
        if (sp.Commodity.Trim() != "")
        {
            sp.HarmonizedCode = "";
            sp.PostTime = DateTime.Now;
            sp.Qty = new Tools().StringToIntDif(num1.Value);
            sp.UnitValue = 0;
            sp.ValueForCustoms = new Tools().StringToDecimalDif(price1.Value);

            new ShipmentService().Insert(sp);
        }
        if (name2.Value.Trim() != "")
        {

            sp.Commodity = name2.Value;
            sp.HarmonizedCode = "";
            sp.PostTime = DateTime.Now;
            sp.Qty = new Tools().StringToIntDif(num2.Value);
            sp.UnitValue = 0;
            sp.ValueForCustoms = new Tools().StringToDecimalDif(price2.Value);

            new ShipmentService().Insert(sp);
        }


    }
    #endregion
    #region 状态写入
    private void StateInsert(string Tno)
    {
        string state = stateidhd.Value.Trim();
        if (state != "" && state != ",")
        {

            string[] idlist = state.Split(',');
            string[] statenamelist = statenamehd.Value.Trim().Split(',');
            string[] datelist = datehd.Value.Trim().Split(',');
            string[] gongsilist = gongsihd.Value.Trim().Split(',');
            string[] danhaolist = danhaohd.Value.Trim().Split(',');


            string id = "";
            string name = "";

            Hashtable hs = new Hashtable();

            int ok = 0;
            for (int i = 0; i < idlist.Length; i++)
            {

                if (idlist[i].ToString().Trim() != "")
                {


                    hs.Clear();
                    hs.Add("SepNo", Tno);
                    hs.Add("Date", tool.StringToTime(datelist[i].ToString()));
                    hs.Add("SateID", idlist[i].ToString());
                    hs.Add("RecordDate", DateTime.Now);
                    hs.Add("RecorderID", Session["uid"].ToString());
                    hs.Add("CompanyID", tool.StringToIntDif(gongsilist[i]));
                    hs.Add("CompanyNo", danhaolist[i]);
                    if (new PublicSqlService().Insert(hs, "Tbl_BillStateRec"))
                    {
                        id = idlist[i].ToString();
                        name = statenamelist[i].ToString();
                        //写入成功
                        ok++;
                    }

                }


            }
            if (ok > 0)
            {
                //写入成功过。更新总单据状态

                hs.Clear();

                hs.Add("StateId", id);
                hs.Add("UPEXState", name);

                new PublicSqlService().Update(hs, "Tbl_WayBill", "TrackingNo='" + Tno + "'");
            }



        }
    }

    //留言写入
    private void InsertLiuyan(string Tno)
    {


        if (liuyanhd.Value.Trim() != "" && liuyanhd.Value.Trim() != ",")
        {

            string[] ly = liuyanhd.Value.Trim().Split(',');
            Hashtable hs = new Hashtable();
            for (int i = 0; i < ly.Length; i++)
            {

                if (ly[i].ToString().Trim() != "")
                {
                    hs.Add("Tno", Tno);
                    hs.Add("Content", ly[i]);
                    hs.Add("PostUser", "公司");
                    hs.Add("UserIsRead", 0);
                    hs.Add("UPEXIsRead", 1);
                    hs.Add("PostDate", DateTime.Now);
                    hs.Add("Attachment", "");//附件
                    hs.Add("PostID", Session["uid"].ToString());

                    new PublicSqlService().Insert(hs, "Tbl_Discuss");


                }
            }

        }


    }
    #endregion
    protected void Okbtn_Click(object sender, ImageClickEventArgs e)
    {
        ToInsert();
    }
    protected void insertly_Click(object sender, ImageClickEventArgs e)
    {

        if (liuyanneirong.Value.Trim() == "")
        {
            Tools.OpenWindow(this, "请输入留言内容");
            return;
        }
        Hashtable hs = new Hashtable();
        hs.Add("Tno", Request.QueryString["tno"]);
        hs.Add("Content", liuyanneirong.Value);
        hs.Add("PostUser", "公司");
        hs.Add("UserIsRead", 0);
        hs.Add("UPEXIsRead", 1);
        hs.Add("PostID", Session["uid"].ToString());
        hs.Add("PostDate", DateTime.Now);

        UploadFile up = new UploadFile("jpg,gif,bmp,doc,xls", 1000, "\\Temp\\");
        string att = "";

        if (imgfier.FileName.Trim() != "")
        {
            if (up.UpLoad(imgfier))
            {
                att = up.FileName;
            }
        }
        hs.Add("Attachment ", att);
        new PublicSqlService().Insert(hs, "Tbl_Discuss");
        BindLiuYan(Request.QueryString["tno"].ToString());
        liuyanneirong.Value = "";
    }
    protected void delbtn_Click(object sender, ImageClickEventArgs e)
    {
        if (AdminCheck.HaveRight(this, "41"))
        {
            if (new PublicSqlService().Del("Tbl_WayBill", "TrackingNo='" + Request.QueryString["Tno"].ToString().Trim() + "'") == 1)
            {

       Response.Redirect("BillManaga.aspx");

            }
            else
            {

                Tools.OpenWindow(this, "删除失败！当前单据已经不允许删除");
            }
        }
        else
        {


            if (new PublicSqlService().Del("Tbl_WayBill", "TrackingNo='" + Request.QueryString["Tno"].ToString().Trim() + "' and StateID=1") == 1)
            {
                Response.Redirect("BillManaga.aspx");

            }
            else
            {

                Tools.OpenWindow(this, "删除失败！当前单据已经不允许删除");
            }
        }
    }
}
